package M_V.MSI.OP.SM.AOP.MEC.SIQ.SM.OSU.E;

import M_V.MS.OP.SM.AOP.MEC.SIQ.cache.DetaDBBufferCache_M;
import O_V.OP.SM.AOP.MEC.SIQ.SM.reflection.Cell;
import O_V.OP.SM.AOP.MEC.SIQ.SM.reflection.Row;
import S_A.pheromone.IMV_SQI;
import org.json.JSONObject;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

/*
 * 个人著作权人, 作者 罗瑶光, 浏阳
 * yaoguangluo@outlook.com, 313699483@qq.com, 2080315360@qq.com,
 * (lyg.tin@gmail.com2018年回国后因国内G网屏蔽不再使用）
 * 15116110525-浏阳德塔软件开发有限公司-创始人-法人-总经理-永久非盈利-
 * 430181198505250014, G24402609, EB0581342
 * 204925063, 389418686, F2406501, 0626136
 * 湖南省 浏阳市 集里街道 神仙坳社区 大塘冲一段路 208号 阳光家园别墅小区 第十栋别墅 第三层
 * */
public class IU_Rows_E_X_IU_RowByTablePathAndIndex {
	public static IMV_SQI insertRowByTablePathAndIndex(String tablePath,
			String pageIndex, JSONObject culumnOfNewRow) {
		String[] sets = tablePath.split("/");
		int rowInsertIndex = Integer.parseInt(pageIndex);
		File fileDBTable = new File(tablePath);
		if (fileDBTable.isDirectory()) {
			String DBTableRowsPath = tablePath + "/rows";
			File fileDBTableRowsPath = new File(DBTableRowsPath);
			if (fileDBTableRowsPath.isDirectory()) {
				Row row = new Row();
				IMV_SQI cells = new IMV_SQI();
				row.I_Cells(cells);
				String DBTableRowIndexPath = DBTableRowsPath + "/row"
						+ rowInsertIndex;
				File readDBTableRowIndexFile = new File(DBTableRowIndexPath);
				if (!readDBTableRowIndexFile.exists()) {
					readDBTableRowIndexFile.mkdir();
					Iterator<String> it = culumnOfNewRow.keys();
					while (it.hasNext()) {
						String culumnName = it.next();
						String culumnValue = culumnOfNewRow
								.getString(culumnName);
						String needCreatCulumnPath = DBTableRowIndexPath + "/"
								+ culumnName;
						File needCreatCulumn = new File(needCreatCulumnPath);
						needCreatCulumn.mkdir();
						FileWriter fileWriter;
						try {
							fileWriter = new FileWriter(
									needCreatCulumnPath + "/value.lyg", true);
							fileWriter.write(
									null == culumnValue ? "" : culumnValue);
							fileWriter.close();
							// buffer reflection update
							Cell cell = new Cell();
							cell.I_CellValue(
									null == culumnValue ? "" : culumnValue);
							row.putCell(culumnName, cell);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					String needCreatCulumnPath = DBTableRowIndexPath
							+ "/is_delete_0";
					File needCreatCulumn = new File(needCreatCulumnPath);
					needCreatCulumn.mkdir();
				}
				DetaDBBufferCache_M.db.getBase(sets[sets.length - 2])
						.getTable(sets[sets.length - 1])
						.putRow("row" + rowInsertIndex, row);
			}
		}
		IMV_SQI output = new IMV_SQI();
		output.put("totalPages", rowInsertIndex);
		return output;
	}

}
